package com.leenmvc.core.utils.http;

import com.alibaba.fastjson.JSONObject;
import com.leenmvc.core.base.result.Result;
import com.leenmvc.core.base.result.ResultCode;
import com.leenmvc.core.config.filter.GlobalFilter;
import com.leenmvc.core.init.Constant;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Http工具类
 *
 * @author leen
 */
public class HttpContextUtils {

    private static Logger logger = LoggerFactory.getLogger(HttpContextUtils.class);

    public static HttpServletRequest getHttpServletRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        }

        return ((ServletRequestAttributes) requestAttributes).getRequest();
    }

    public static <K,V> Map<K, V> getParameterMap(HttpServletRequest request) {
        Enumeration<String> parameters = request.getParameterNames();
        Map<K, V> params = new HashMap<>();
        while (parameters.hasMoreElements()) {
            String parameter = parameters.nextElement();
            String value = request.getParameter(parameter).trim();
            if (StringUtils.isNotBlank(value)) {
                params.put((K)parameter, (V)value);
            }
        }
        return params;
    }

    public static String getDomain() {
        HttpServletRequest request = getHttpServletRequest();
        StringBuffer url = request.getRequestURL();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
    }

    public static String getOrigin() {
        HttpServletRequest request = getHttpServletRequest();
        return request.getHeader(HttpHeaders.ORIGIN);
    }

    public static String getToken() {
        HttpServletRequest request = getHttpServletRequest();
        if (request != null)
        return request.getHeader("token");
        return null;
    }

    public static String getLanguage() {
        //默认语言
        String defaultLanguage = "zh-CN";
        //request
        HttpServletRequest request = getHttpServletRequest();
        if (request == null) {
            return defaultLanguage;
        }

        // 请求语言
        defaultLanguage = request.getHeader(HttpHeaders.ACCEPT_LANGUAGE);
        if (defaultLanguage == null) {
            defaultLanguage = "zh-CN";
        } else if (defaultLanguage.contains("zh-CN")) {
            defaultLanguage = "zh-CN";
        } else if(defaultLanguage.contains("en-US")) {
            defaultLanguage = "en-US";
        }

        return defaultLanguage;
    }

    /**
     * 返回JSON数据到前端
     *
     * @param httpRequest
     * @param response
     * @param message
     */
    public static void returnJSON(HttpServletRequest httpRequest, HttpServletResponse response, String message) {
        response.setContentType("text/json;charset=UTF-8"); //上面两句的综合
        Result result = new Result();
        result.setCode(250);
        result.setMsg(message);
        String o = JSONObject.toJSONString(result);
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            out.write(o.getBytes("UTF-8"));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回本地html到前端
     *
     * @param httpRequest
     * @param response
     * @param url
     */
    public static void returnHtmlPage(HttpServletRequest httpRequest, HttpServletResponse response, String url) {
        try {
            String viewPath = Constant.COMMON_URL_BASE_VIEW + url;
            httpRequest.getRequestDispatcher(viewPath).forward(GlobalFilter.getRequestParameterWrapper(httpRequest, viewPath), response);
            return;
        } catch (IOException | ServletException e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 返回本地html到前端
     *
     * @param httpRequest
     * @param response
     * @param resultCode
     */
    public static void returnCodePage(HttpServletRequest httpRequest, HttpServletResponse response, ResultCode resultCode) {
        try {
            String viewPath = Constant.COMMON_URL_BASE_VIEW + "/error/404.html";
            switch (resultCode) {
                case NOT_FOUND:
                    viewPath = Constant.COMMON_URL_BASE_VIEW + "/error/404.html";
                    break;
                case FAIL:
                    viewPath = Constant.COMMON_URL_BASE_VIEW + "/error/500.html";
                    break;
                case NO_AUTHORIZED:
                    viewPath = Constant.COMMON_URL_BASE_VIEW + "/error/401.html";
                    break;
                default:
                    break;
            }

            httpRequest.getRequestDispatcher(viewPath).forward(GlobalFilter.getRequestParameterWrapper(httpRequest, viewPath), response);
            return;
        } catch (IOException | ServletException e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 返回本地html到前端
     *
     * @param response
     */
    public static void returnHtml(HttpServletResponse response, String html) {
        response.setContentType("text/html;charset=UTF-8");
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            out.write(html.getBytes("UTF-8"));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 方式一
    public static String readAsChars(HttpServletRequest request) {

        BufferedReader br = null;
        StringBuilder sb = new StringBuilder("");
        try {
            br = request.getReader();
            String str;
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }  finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

    // 方法二
    public static void readAsChars2(HttpServletRequest request) {
        InputStream is = null;
        try {
            is = request.getInputStream();
            StringBuilder sb = new StringBuilder();
            byte[] b = new byte[4096];
            for (int n; (n = is.read(b)) != -1; ) {
                sb.append(new String(b, 0, n));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    // 二进制读取
    public static byte[] readAsBytes(HttpServletRequest request) {
        int len = request.getContentLength();
        if(len == -1) return null;
        byte[] buffer = new byte[len];
        ServletInputStream in = null;

        try {
            in = request.getInputStream();
            in.read(buffer, 0, len);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return buffer;
    }


    /**
     * 获取IP地址
     *
     * 使用Nginx等反向代理软件， 则不能通过request.getRemoteAddr()获取IP地址
     * 如果使用了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP地址，X-Forwarded-For中第一个非unknown的有效IP字符串，则为真实IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String unknown = "unknown";
        String ip = null;
        try {
            ip = request.getHeader("x-forwarded-for");
            if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } catch (Exception e) {
            logger.error("HttpContextUtils ERROR ", e);
        }

        return ip;
    }

}